import { Breadcrumb } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import styles from './InitBreadcrumb.scss';

interface initBreadcrumb {
  path?: string;
  list?: Array<object>;
  breadcrumbWidth?: number;
  resizeInterval?: () => string | number | object | Array<object>;
  breadcrumRef?: number;
  newFontSize?: number;
  font?: 'default' | 'large' | 'small';
  initWidth?: number;
}

const InitBreadcrumb: React.FC<initBreadcrumb> = ({
  list = [],
  font = 'default',
}) => {
  const [breadcrumbWidth, setbreadcrumbWidth] = useState(0);
  const [newFontSize, setnewFontSize] = useState(0);
  const breadcrumRef = useRef(16);
  const initWidth = 0;

  useEffect(() => {
    if (breadcrumRef.current) {
      const handleResize = () => {
        if (font === 'large') {
          setnewFontSize(16);
        } else if (font === 'small') {
          setnewFontSize(12);
        } else {
          setnewFontSize(14);
        }
        setbreadcrumbWidth(
          breadcrumRef.current.offsetWidth
            ? breadcrumRef.current.offsetWidth
            : initWidth,
        );
      };

      // 每 200 毫秒检查一次元素的尺寸
      const resizeInterval = setInterval(handleResize, 200);

      // 清除定时器
      return () => {
        clearInterval(resizeInterval);
      };
    }
  }, []);

  const breadcrumbClass =
    'BreadcrumbWidth' + Math.ceil(breadcrumbWidth * list.length) + 'px';
  const breadcrumbStyle = {
    width: `${Math.ceil(breadcrumbWidth * list.length)}px`,
    fontSize: newFontSize + 'px',
  };

  function handleClick(item: string | undefined) {
    if (item) {
      history.replace(item);
    }
  }
  return (
    <>
      <Breadcrumb
        className={breadcrumbClass}
        style={breadcrumbStyle}
        separator=">"
        items={list.map((ele) => ({ ...ele }))}
        itemRender={(route, index) => (
          <a
            ref={breadcrumRef}
            key={index}
            className={styles.children}
            onClick={() => handleClick(route.path)}
          >
            {route.title}
          </a>
        )}
      />
    </>
  );
};

export default InitBreadcrumb;
